<?php
/**
 * Created by PhpStorm.
 * User: 睿
 * Date: 2017-12-15
 * Time: 16:20
 */

namespace app\store\controller;


use controller\BasicAdmin;
use think\Db;

class User extends BasicAdmin
{
    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'User';

    /**
     * 本店会员
     * @return array|string
     */
    public function index()
    {
        $this->title = '本店会员';
        $get = $this->request->get();

        $store_id = session('user')['store_id'];

        $db = Db::name($this->table)->alias('a')->join('ys_sys_level b','a.level_id=b.id','LEFT')->where('a.store_id', $store_id)->where('a.is_deleted',0)->order('a.uid desc')->field('a.*,b.title');

        foreach (['realname'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }

        $qiniu = config('qiniu');
        $this->assign('qiniu', $qiniu['yangshi']);          //七牛样式后缀

        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    添加 -- 编辑会员
     * 2018-06-01
     */
    public function add_edit_member(){
        if(request()->isPost()){
            $post = input('post.');
            $reg_mobile = '/^1[3-9][0-9]{9}$/';
            $reg_password = '/^[a-zA-Z0-9_]{6,16}$/';
            if(empty($post['realname'])){
                $this->error('请输入真实姓名','');
            }
//            if($post['mobile'] == ''){
//                $this->error('请填写手机号','');
//            }
            if(!empty($post['mobile'])){
                if(!preg_match($reg_mobile,$post['mobile'])){
                    $this->error('手机格式错误','');
                }
                $mobile = db('user')->where('mobile',$post['mobile'])->find();
                if(!empty($mobile)){
                    $this->error('该手机号已被占用，请更换手机号','');
                }
            }

            if(empty(trim($post['password']))){
                $this->error('请填写登录密码','');
            }
            if(!preg_match($reg_password,$post['password'])){
                $this->error('密码格式错误，必须是字母数字下划线6~16位组合','');
            }
            if($post['password'] != $post['repassword']){
                $this->error('两次密码输入不一致，请重新输入','');
            }



            $user = db('user')->order('uid desc')->limit(1)->value('uid');
            $cur_uid = $user+1;
            $pay_code = '5270'.sprintf("%04d", $cur_uid);         //会员支付码
            if(!empty($post['pay_code'])){
                $pay_code_res = db('user')->where('pay_code',$post['pay_code'])->find();
                if(!empty($pay_code_res)){
                    $this->error('该会员卡号已被占用，请重新填写','');
                }else{
                    $pay_code = $post['pay_code'];
                }
            }else{
                $pay_code = '5270'.sprintf("%04d", $cur_uid);         //会员支付码
            }
            $data_arr = [
                't_pid'=>0,
                'pid'=>0,
                'mobile'=>$post['mobile'],
                'realname'=>$post['realname'],
                'nickname'=>$post['realname'],
                'password'=>md5($post['password']),
                'pay_code'=>$pay_code,
                'addtime'=>time(),
                'pay_points'=>100,
                'level_id'=>1,
                'store_id'=>session('user')['store_id']
            ];
            $res = $u_id = db('user')->insertGetId($data_arr);


            $user_point_log = [
                'uid'=>$u_id,
                'store_id'=>session('user.store_id'),
                'uidtype'=>2,
                'signid'=>4,
                'type'=>1,
                'point'=>100,
                'curpoint'=>100,
                'type_cn'=>'注册会员赠送积分',
                'whname'=>'后台操作',
                'remark'=>'注册会员赠送积分',
                'addtime'=>time(),
            ];

            db('user_point_log')->insert($user_point_log);

            $res>0?$this->success('保存成功',''):$this->error('保存失败','');
        }else{
            $id = input('id');
            $info = db('user')->where('uid',$id)->find();      //会员信息

            $this->assign('vo',$info);
            return $this->fetch();
        }
    }

    /**
     * 用户编辑
     */
    public function edit()
    {
        if(request()->isPost()){
            $post = input('post.');
            if(isset($post['uid'])){
                $post['nickname'] = $post['realname'];
                $result = db('user')->where(['uid'=>['neq',$post['uid']],'mobile'=>$post['mobile']])->count();
                if($result>0){      //有重复的手机号
                    $this->error('该手机号已被占用，请重新输入','');
                }

                $res = db('user')->where('uid',$post['uid'])->update($post);
                $res!==false?$this->success('保存成功',''):$this->error('保存失败，请稍后再试','');
            }
        }
        return $this->_form($this->table, 'form');
    }


    /**
     * 表单数据默认处理
     * @param array $data
     */
    public function _form_filter(&$data)
    {
        if ($this->request->isPost()) {
            if (isset($data['uid'])) {
//                unset($data['mobile']);

            } elseif (Db::name($this->table)->where(['mobile' => $data['mobile']])->count() > 0) {
                $this->error('会员手机号已经存在，请使用其它号码！');
            }
        }
    }

    /**
     * 充值
     * 会员充值不获得积分，只获得等级
     */
    public function recharge()
    {
        if (request()->ispost()){
            $post = input('post.');
            $user = db('user')->find($post['uid']);
            if(empty($post['user_money'])){
                $this->error('请输入变更金额','');
            }
            if(!isset($post['type'])){
                $this->error('请选择变更类型','');
            }
            if(empty($post['remark'])){
                $this->error('请输入备注','');
            }
            if($post['type'] == 1){     //充值
                $data_arr['user_money'] = $post['user_money'] + $user['user_money'];
                $level_id = user_level($post['user_money']);           //会员充值
                if($user['level_id'] < $level_id){
                    $data_arr['level_id'] = $level_id;
                }
                $log = [
                    'uid' => $post['uid'],
                    'admin_id' => session('user')['id'],
                    'store_id' => session('user')['store_id'],
                    'uname' => $user['realname'],
                    'amount' => $post['user_money'],
                    'cur_amount' => $user['user_money'] + $post['user_money'],
                    'sign' => 1,
                    'chargetype' => 2,
                    'addtime' => time(),
                    'charge_cn' => $post['remark'],
                ];
                db('user_wallet_log')->insert($log);
                $res = db('user')->where('uid',$post['uid'])->update($data_arr);
            }else{
                $data_arr['user_money'] = $user['user_money'] - $post['user_money'];
                $log = [
                    'uid' => $post['uid'],
                    'admin_id' => session('user')['id'],
                    'store_id' => session('user')['store_id'],
                    'uname' => $user['realname'],
                    'amount' => $post['user_money'],
                    'cur_amount' => $user['user_money'] - $post['user_money'],
                    'sign' => 1,
                    'chargetype' => 1,
                    'addtime' => time(),
                    'charge_cn'=>$post['remark']
                ];
                db('user_wallet_log')->insert($log);
                $res = db('user')->where('uid',$post['uid'])->update($data_arr);
            }

            //积分规则
//            $sys_point = db('sys_point')->where('id',3)->find();
//            $point_rate = $sys_point['point']/100;
//            $point = ceil($post['user_money'] * $point_rate);
//
//            $user_money = db('user')->where('uid', $post['uid'])->setInc('user_money', $post['user_money']);
//            $pay_points = db('user')->where('uid', $post['uid'])->setInc('pay_points', $point);
//            $level_point = db('user')->where('uid', $post['uid'])->setInc('level_point', $point);
//            //余额日志
//            $log = db('user_wallet_log')->insert([
//                'uid' => $post['uid'],
//                'admin_id' => session('user')['id'],
//                'store_id' => session('user')['store_id'],
//                'uname' => $user['realname'],
//                'amount' => $post['user_money'],
//                'cur_amount' => $user['user_money'] + $post['user_money'],
//                'sign' => 1,
//                'chargetype' => 2,
//                'addtime' => time()
//            ]);
//            //积分日志
//            $point_log = db('user_point_log')->insert([
//                'uid' => $post['uid'],
//                'admin_id' => session('user')['id'],
//                'store_id' => session('user')['store_id'],
//                'uidtype' => 2,
//                'type' => 1,
//                'point' => $point,
//                'curpoint' => $user['pay_points'] + $point,
//                'addtime' => time()
//            ]);

//            if ($user_money !== false && $pay_points !== false && $level_point !== false && $log !== false && $point_log !== false)
                $res!==false?$this->success('保存成功', ''):$this->error('保存失败','');
        }
        return $this->_form($this->table, 'recharge');
    }

    /**
     * 会员充值
     * @return mixed
     */
    public function rechageindex()
    {
        $get = $this->request->get();

        if (isset($get['realname']))
            $db = Db::name($this->table)->where('realname', $get['realname'])->select();
        else
            $db = null;

        $qiniu = config('qiniu');
        $this->assign('qiniu', $qiniu['yangshi']);          //七牛样式后缀
        $this->assign('list', $db);
        $this->assign('title', '会员充值');
        return view();
    }

    /**
     * 积分兑换
     */
    public function exchange()
    {
        if (request()->ispost()) {
            $post = input('post.');
            $user = db('user')->find($post['uid']);
            if(empty($post['pay_points'])){
                $this->error('请输入变更的积分','');
            }
            if(!isset($post['type'])){
                $this->error('请输入变更类型','');
            }
            if(empty($post['remark'])){
                $this->error('请输入备注','');
            }

            if($post['type'] == 1){         //增加积分
                //积分日志
                $point_log = [
                    'uid' => $post['uid'],
                    'admin_id' => session('user')['id'],
                    'store_id' => session('user')['store_id'],
                    'uidtype' => 2,
                    'type' => 0,
                    'point' => -$post['pay_points'],
                    'curpoint' => $user['pay_points'] + $post['pay_points'],
                    'remark' => $post['remark'],
                    'type_cn' => $post['remark'],
                    'addtime' => time()
                ];
                $data_arr = [
                    'pay_points'=>$user['pay_points']+$post['pay_points']
                ];
            }else{
                //积分日志
                $point_log =[
                    'uid' => $post['uid'],
                    'admin_id' => session('user')['id'],
                    'store_id' => session('user')['store_id'],
                    'uidtype' => 2,
                    'type' => 0,
                    'point' => -$post['pay_points'],
                    'curpoint' => $user['pay_points'] - $post['pay_points'],
                    'remark' => $post['remark'],
                    'type_cn' => $post['remark'],
                    'addtime' => time()
                ];
                $data_arr = [
                    'pay_points'=>$user['pay_points']-$post['pay_points']
                ];
            }
//            if ($post['pay_points'] > $user['pay_points'])
//                $this->error('积分不足！');

            db('user_point_log')->insert($point_log);
            $res = db('user')->where('uid', $post['uid'])->update($data_arr);
            $res!==false?$this->success('变更成功',''):$this->error('变更失败','');

//            if ($pay_points !== false && $point_log !== false)
//                $this->success('兑换成功！', '');
        }
        return $this->_form($this->table, 'exchange');
    }

    /**
     * 积分日志
     */
    public function li()
    {
        $uid = input('uid');
        $user = db('user')->where('uid', $uid)->find();
        $this->title = '积分日志-' . $user['realname'];

        $db = db('user_point_log')->where('uid', $uid)->order('id desc');

        return parent::_list($db);
    }

    /**
     * 与余额日志
     */
    public function log()
    {
        $uid = input('uid');
        $user = db('user')->where('uid', $uid)->find();
        $this->title = '余额日志-' . $user['realname'];

        $db = db('user_wallet_log')->where('uid', $uid)->order('id desc');

        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    修改密码
     * 2018-05-17
     */
    public function edit_pass(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $reg = '/^[a-zA-Z0-9_]{6,16}$/';
            if(empty($post['password'])){
                $this->error('请输入新密码','');
            }
            if(empty($post['repassword'])){
                $this->error('请输入确认密码','');
            }
            if($post['password'] != $post['repassword']){
                $this->error('两次密码输入不一致，请重新输入');
            }
            if(!preg_match($reg,$post['password'])){
                $this->error('密码格式错误，必须是字母数字下划线6~16为组合');
            }
            $password = md5($post['password']);
            $res = db('user')->where('uid',$post['uid'])->update(['password'=>$password]);
            $res!==false?$this->success('修改成功',''):$this->error('修改失败','');
        }else{
            $id = input('uid');
            $vo = db('user')->where('uid',$id)->find();

            $this->assign('id',$id);
            $this->assign('vo',$vo);
            return $this->fetch();
        }
    }

    /**
     * @Author  lingyun
     * @Desc    设置会员状态
     */
    public function set_status(){
        $id = input('id');
        $status = db('user')->where('uid',$id)->value('status');
        $status = abs($status-1);
        $res = db('user')->where('uid',$id)->update(['status'=>$status]);
        $res!==false?$this->success('设置成功',''):$this->error('设置失败，请稍后再试','');
    }


}